currentRankablePopover = "";

function buttnState(type, entity) {
    if (typeof my_thumbs != "undefined") {
        for (thumb in my_thumbs) {
            if (my_thumbs[thumb].type == entities[type] && my_thumbs[thumb].entity == entity) {
                return my_thumbs[thumb].rank;
            }
        }
    }
    return -1;
}

$('.movie-search-btn').popover({
	animation: false,
	placement: 'right',
	trigger: 'manual',
	title: 'Error <button class="close mn-po-close" data-parent-id="movie-search-btn">&times;</button>',
	content: "Please choose a movie from the list.",
	delay: 0
});

$('#profile-edit-submit').popover({
	animation: false,
	placement: 'left',
	trigger: 'manual',
	title: 'Enter password',
	content: '<input type="password" id="pop-pass"></input><button class="btn btn-primary" id="profile-edit-pass-submit">Go</button>',
	delay: 0
});

$('#login_pass').popover({
	animation: false,
	placement: 'bottom',
	trigger: 'manual',
	title: 'Error <button class="close mn-po-close" data-parent-id="login_pass">&times;</button>',
	content: passError,
	delay: 0
});

$('#login_email').popover({
	animation: false,
	placement: 'bottom',
	trigger: 'manual',
	title: 'Error <button class="close mn-po-close" data-parent-id="login_email">&times;</button>',
	content: mailError,
	delay: 0
});

$('#add-friend').popover({
	animation: false,
	placement: 'right',
	trigger: 'manual',
	title: 'Error <button class="close mn-po-close" data-parent-id="add-friend">&times;</button>',
	content: "Please choose a name from the list.",
	delay: 0
});

$('.movie-toolbar').tooltip({
    title: function() { return $(this).data('desc'); },
    placement: 'bottom'
});

$('.rankable').data('toggle', 'clickover');

function generateRankableTitle(rankable) {
    var str = rankable.data('rankable-type') + ': ';
    str += rankable.text();
    return str;
}

function generateRankableContent(rankable) {

    var btnState = buttnState(rankable.data('rankable-type'), rankable.data('rankable-value')),
        thumbsup = "",
        thumbsdown = "";
    if (btnState == 1) {
        thumbsup = "active";
    } else if (btnState == 0) {
        thumbsdown = "active";
    }

    var str = '<p style="text-align: center;">';
    str += '<button class="btn btn-large btn-rank btn-rank-thumbs-up '+thumbsup+'" data-dismiss="clickover"';
    str += ' style="margin-right: 10px;">';
    str += '<i class="icon-thumbs-up"></i></button>';
    str += '<button class="btn btn-large btn-rank btn-rank-thumbs-down '+thumbsdown+'" data-dismiss="clickover">';
    str += '<i class="icon-thumbs-down"></i></button></p>';
    return str;
}

$('.rating-star').live('mouseenter', function(e) {
    e.preventDefault();
    var num = parseInt(this.id.substring(12));
    
    var $stars = $('.rating-star');
    $stars.addClass("icon-star-empty").removeClass("icon-star");
    $stars = $stars.slice(0, num);
    $stars.removeClass("icon-star-empty").addClass("icon-star");
});

$('body').on('click', '.rating-star', function(e) {
    e.preventDefault();
    var num = parseInt(this.id.substring(12));
    
    movieRating = num;
    
    var starData = { rating: num };
    if (currentRankablePopover.data && currentRankablePopover.data('taste-movieid')) {
        starData.userid = myid;
        starData.mid = currentRankablePopover.data('taste-movieid');
        currentRankablePopover.data('taste-curr-rank', num)
    } else {
        starData.userid = ownerId;
        starData.mid = movieId;
    }
    
    $.ajax({
        type: "get",
        url: "mn_db_rating.php", 
        data: starData
    });
});

function updateRatingValue(value) {
    var $stars = $('.rating-star:visible');
    $stars.addClass("icon-star-empty").removeClass("icon-star");
    $stars = $stars.slice(0, value);
    $stars.removeClass("icon-star-empty").addClass("icon-star");
}

function defaultRatingValue(flag) {
    if (flag || flag === 0) {
        updateRatingValue(flag);
    } else {    
        if (typeof movieRating == 'undefined') return;
        updateRatingValue(movieRating);
    }
}

$('.rating').on('mouseleave', function(e) {
    e.preventDefault();
    
    defaultRatingValue();
});

$('body').on('mouseleave', '.rating.po-rating', function(e) {
    e.preventDefault();
    
    if (currentRankablePopover.data) {
        defaultRatingValue(currentRankablePopover.data('taste-curr-rank'));
    } else {
        defaultRatingValue(0);
    }
});

$('.rankable').not('.my-taste-img').popover({
    trigger: 'manual',
    template: '<div class="popover rankable-popover"><div class="arrow"></div><div class="popover-inner"  style="width: auto;"><h6 class="popover-title"></h6><div class="popover-content"><p></p></div></div></div>',
    title: function() { return generateRankableTitle($(this)); },
    content: function() { return generateRankableContent($(this)); }
});

function generateTastePopverTitle(elem) {
    return elem.data('taste-title');
}

function generateTastePopverContent(elem) {
    var str = '<div class="taste-popover-stars">';
    str += '<div class="rating po-rating">';
    str += '<i class="icon-star-empty rating-star po-rating-star" id="rating-star-1"></i>';
    str += '<i class="icon-star-empty rating-star po-rating-star" id="rating-star-2"></i>';
    str += '<i class="icon-star-empty rating-star po-rating-star" id="rating-star-3"></i>';
    str += '<i class="icon-star-empty rating-star po-rating-star" id="rating-star-4"></i>';
    str += '<i class="icon-star-empty rating-star po-rating-star" id="rating-star-5"></i>';
    str += '<i class="icon-star-empty rating-star po-rating-star" id="rating-star-6"></i>';
    str += '<i class="icon-star-empty rating-star po-rating-star" id="rating-star-7"></i>';
    str += '<i class="icon-star-empty rating-star po-rating-star" id="rating-star-8"></i>';
    str += '<i class="icon-star-empty rating-star po-rating-star" id="rating-star-9"></i>';
    str += '<i class="icon-star-empty rating-star po-rating-star" id="rating-star-10"></i>';
    str += '</div></div>';
    
    return str;
}

function refreshPopovers() {
    //$('.rankable.my-taste-img').popover('hide');
    $('.rankable.my-taste-img').popover({
        trigger: 'manual',
        template: '<div class="popover rankable-popover"><div class="arrow"></div><div class="popover-inner"  style="width: auto;"><h6 class="popover-title"></h6><div class="popover-content"><p></p></div></div></div>',
        title: function() { return generateTastePopverTitle($(this)) },
        content: function() { return generateTastePopverContent($(this)) },
        placement: 'right'
    });
}

refreshPopovers();

$('body').on({
    mouseenter: function(e) {
        var $this = $(this);
        if ($this.data('visible')) { return; }
        if ($this.data('in-timer')) {
            clearTimeout($this.data('in-timer'));
        }
        $this.data('in-timer', setTimeout(function() {
            $('.rankable').not($this).popover('hide');
            $('.rating-star.po-rating-star').hide();
            $('.rankable').not($this).data('visible', false);
            $this.popover('show');
            $this.data('in-timer', false);
            $this.data('visible', true);
            currentRankablePopover = $this;
            if ($this.data('taste-curr-rank')) {
                updateRatingValue($this.data('taste-curr-rank'));
            }
        }, 500));
    },
    mouseleave: function(e) {
        var $this = $(this);
        clearTimeout($this.data('in-timer'));
        $this.data('in-timer', false);
        $('.rankable-popover:visible').trigger('mouseleave');
    }
}, '.rankable');

$('.rankable-popover').live({
    mouseenter: function(e) {
        var $this = $(this);
        if ($this.data('in-timer')) {
            clearTimeout($this.data('in-timer'));
            $this.data('in-timer', false)
        }
    },
    mouseleave: function(e) {
        var $this = $(this);
        
        if ($this.data('in-timer')) return;
        $this.data('in-timer', setTimeout(function() {
            $this.fadeOut('fast');
            $('.rankable').data('visible', false);
            $this.data('in-timer', false);
            //currentRankablePopover = "";
        }, 1000));
    }
});

$('.btn-rank').live('click', function(e) {

    var $this = $(this),
        rank;
    
    if ($this.hasClass('btn-rank-thumbs-up')) {
        rank = 1;
    } else if ($this.hasClass('btn-rank-thumbs-down')) {
        rank = 0;
    }
    
    var r_data = {
        userid: myid,
        type: entities[currentRankablePopover.data('rankable-type')],
        unresType: currentRankablePopover.data('rankable-type'),
        entity: currentRankablePopover.data('rankable-value'),
        rank: rank
    }
  
    $.ajax({
        url: 'mn_db_thumbs_save.php',
        type: 'get',
        data: r_data,
        success: function(d) {
            if (d == "Done") {
                my_thumbs.unshift({ type: r_data.type, entity: r_data.entity, rank: r_data.rank })
            }
        }
    });
    
    $this.parent().parent().parent().parent().parent().hide();
    $('.rankable').data('visible', false);
    $this.data('in-timer', false);
    
    e.preventDefault();
});

//friendArray = ["Gilad Artzi", "Yoni Zakin", "Guy Green", "Nir Rotgold", "Amir Kimchy", "Chuck Norris", "Avi Bitter", "Shaul the Dwarf"];
//chosenFriends = [];

function gatherFriendIDs() {
    var i, answer = "";
    for (i = 0; i < chosenFriends.length; i++) {
        answer += fullNameToId[chosenFriends[i]];
        answer += "$";
    }
    return answer;
}

function gatherFriendIDsCommaSep() {
    var i, answer = "";
    for (i = 0; i < chosenFriends.length; i++) {
        answer += fullNameToId[chosenFriends[i]];
        answer += ",";
    }
    return answer;
}

suggestIndex = 0;

function displaySuggestedMovie(image, title, genre, tagline, index) {
    var data = suggestions[index]['moviedata'],
		l;
    chosenMovieId = data.movieid;
    suggestIndex = index;
    image.attr("src", "img/posters/" + data.imdbid + "_small.jpg");
    title.html("<a href='?movie_data&mid=" + data.movieid + "' style='color: black;'>" + data.title + "</a> <small>" + data.year + "</small>");
    genre.text(data.genre);
	if (data.taglinetext) {
		l = data.taglinetext.length;
		data.taglinetext = data.taglinetext.substring(0, 200);
		if (l > 200) {
			data.taglinetext += "...";
		}
		tagline.text(data.taglinetext); 
	}
}

// ###############################################
// #          My-taste data handling             #
// ###############################################

var $myTaste = $('.my-taste'),
    mtFirst = true;

function mtMovie(d) {
    var str = "";
    str += '<img src="img/posters/'+d.imdbid+'_small.jpg" ';
    str += 'alt="Poster" class="rankable my-taste-img" ';
    str += 'data-taste-movieid="'+d.movieid+'" ';
    str += 'data-taste-title="'+d.title+'" ';
    str += 'data-taste-curr-rank="0">';
    return str;
}

function mtOffer($elem) {
    if (mtFirst) $elem.parent().parent().addClass('ajax-loader');
    
    mtElem = $('<div class="my-taste" style="float: left"></div>');
    mtButton = $('.btn-taste-more').button('loading');
    
    $.ajax({
        url: 'mn_db_rating_my_taste.php',
        type: 'get',
        data: { userid: myid },
        dataType: 'json',
        success: function(d) {
            for (i in d) {
                mtElem.append(mtMovie(d[i]));
            }
            $elem.parent().parent().removeClass('ajax-loader');
            $elem.parent().append(mtElem);
            var that = $elem.first();
            if (mtFirst) {
                $('.taste-popover-stars').remove();
                that.remove();
                mtFirst = false;
            }
            else {
                $elem.parent().animate({ marginLeft: '-=' + $elem.width() + 'px' }, 'swing', function() {
                    that.parent().css({ marginLeft: 0 });
                    $('.taste-popover-stars').remove();
                    that.remove();
                });
            }
            refreshPopovers();
            mtButton.button('reset');
        }
    });
}

if ($myTaste.length) mtOffer($myTaste);

$('.btn-taste-more').on('click', function() { mtOffer($('.my-taste')); });

// ###############################################


$(document).ready(function() {
	var numOfEdits = 0;
	if (passError) $('#login_pass').popover('show');
	if (mailError) $('#login_email').popover('show');
	
	if ($('.add-friend-typeahead').length > 0) {
		$('.add-friend-typeahead').typeahead({
			source: friendArray 
		});
	}
	
	if ($('.movie-typeahead').length > 0) {
		$('.movie-typeahead').typeahead({
			source: movieTitles 
		});
	}
	
	$('.movie-search-btn').on('click', function(e) {
		e.preventDefault();
		var typeaheadVal = $('.movie-typeahead').val(); 
		if (movieFullData[typeaheadVal]) {
			window.location = "?movie_data&mid=" + movieFullData[typeaheadVal].movieid;
		}		
		else {
			$(this).popover('show');
		}
	});
	
	$('.my-taste-img').live('click', function(e) {
		e.preventDefault();
		
		window.location = "?movie_data&mid=" + $(this).data('taste-movieid');
	});
	
	$friendTable = $('#friend-table').children(0);
	$searchFriend = $('#search-friend');
	$finishButton = $('.finish-button');
	
	$('.mn-po-close').live('click', function() {
		var parent = '#' + $(this).data('parent-id');
		$(parent).popover('hide');
	});
	
	$('#reg-cancel-btn').click(function() {
		var parent = $(this).parent().parent().parent();
		parent.find('input').not('input[type=hidden]').val("");
	});
	
	$('.datepicker').datepicker();
	
	$('#add-friend').click(function(e) {
		e.preventDefault();
        chosenFriends.push($searchFriend.val());
		var index = friendArray.indexOf($searchFriend.val());
		if (index == -1) { $('#add-friend').popover('show'); return; }
		friendArray.splice(index, 1);
		if ($searchFriend.val().length == 0) return;
		$friendTable.append("<tr><td>" + $searchFriend.val() + "</td><td><a href=\"#\" class=\"remove-friend\">Remove</a></td></tr>");
		$searchFriend.val("");
	});
	
	$('.remove-friend').live('click', function(e) {
		e.preventDefault();
		var $this = $(this),
			name = $this.parent().prev().text()
            index = chosenFriends.indexOf(name);
		friendArray.push(name);
		console.log(index + " " + name);
        chosenFriends.splice(index, 1);
		console.log("after: " + chosenFriends);
		$this.parent().parent().remove();
	});
    
    suggestions = [];

	$('.chosen-button').click(function(e) {
        var image = $('.chosen-image'),
            title = $('.chosen-title'),
            genre = $('.chosen-genre'),
            tagline = $('.chosen-tagline'),
            btn = $(this);

        btn.button('loading');
        $.ajax({
            url: 'mn_db_getmovie.php',
            data: { friends: gatherFriendIDsCommaSep() },
            type: "get",
            dataType: "json",
            success: function(data) {
				btn.button('reset');
                suggestions = data;
                
                displaySuggestedMovie(image, title, genre, tagline, 0);
                
                $('.chosen-movie').show();
                //$finishButton.show();
                $('#suggestion-modal').modal('show');
            }
        });

        e.preventDefault();
    });
    
    $('.another-movie').click(function(e) {
        var image = $('.chosen-image'),
            title = $('.chosen-title'),
            genre = $('.chosen-genre'),
            tagline = $('.chosen-tagline');
            
        displaySuggestedMovie(image, title, genre, tagline, suggestIndex + 1);

        e.preventDefault();
    });
    
    $('.chosen-button').click(function(e) {
        var image = $('.chosen-image'),
            title = $('.chosen-title'),
            genre = $('.chosen-genre'),
            tagline = $('.chosen-tagline'),
            btn = $(this);

        btn.button('loading');
        
        e.preventDefault();
    });
    
    $finishButton.click(function(e) {
        var args = {};
        args.movieid = chosenMovieId;
        args.date = $('.chosen-date').val();
        args.friends = gatherFriendIDs();
        
        $.ajax({
            url: 'mn_db_save.php',
            type: 'GET',
            data: args,
            success: function(data) {
                if (data == "Success") {
					$('#suggestion-modal').modal('hide');
					setTimeout(function() { window.location = "?events"; }, 500);
				}
            }
        });
        
        e.preventDefault();
    });
    
    defaultRatingValue();
    
	$('.actor-row').slice(10).hide();
	
	$(".show-all").click(function(e) {
		e.preventDefault();
		$('.actor-row').show();
	});
	
	$(".icon-pencil").live('click', function(){
		if (numOfEdits == 0){
			$(".form-actions").show();
		}
		numOfEdits++;
		parent = $(this).parent().parent();
		fieldName = parent.find(".field").text();
		//parent.data("backup", parent.children(".personalData").text());
		parent.children(".personalData").remove();
		parent.find(".edit").removeClass("icon-pencil");
		parent.find(".edit").addClass("icon-remove");
		parent.children('.field').after("<div class='span2 editData'><input type='text' class='input-small' name='" + fieldName + "'></input></div>");
	});
	
	$(".icon-remove").live('click', function(){
		numOfEdits--;
		if (numOfEdits == 0){
			$("#profile-edit-submit").popover("hide");
			$(".form-actions").hide();
		}
		parent = $(this).parent().parent();
		var restoreData = parent.data("backup");
		parent.children(".editData").remove();
		parent.find(".edit").removeClass("icon-remove");
		parent.find(".edit").addClass("icon-pencil");
		parent.children('.field').after("<div class='span2 personalData'>" + restoreData + "</div>");
	});
	
	$(".profile-edit-cancel").on("click", function(){
		$(this).parent().parent().parent().find(".icon-remove").click();
	});
	
	$("#profile-edit-submit").on("click", function() {
		$(this).popover("toggle");
	});
	
	$("#profile-edit-pass-submit").live("click", function() {
		$("#oldEmail").val($("#email").data("backup"));
		$("#pass").val($("#pop-pass").val());
		alert($("#pass").val());
		$("#edit-form").submit();
	});
});